<template>
  <div class="container">
    <div class="container">
      <!-- 表单区域 -->
      <section class="app-main">
        <SeachTop>
          <template #left>
            <p>库区名称</p>
          </template>
          <template #middle>
            <p>库位名称</p>
          </template>
        </SeachTop>
        <div class="bottom">
          <!-- 表格区域 -->
          <el-card>
            <div class="btn">
              <div class="left">
                <el-button type="primary" round class="new" @click="add">新增库位</el-button>
              </div>
              <div>
                <el-button round class="new">下载库位模板</el-button>
                <el-button round class="new" @click="importload">导入库位信息</el-button>
              </div>
            </div>
            <el-table :data="locationList" border style="width: 100%">
              <el-table-column
                type="index"
                label="序号"
                width="90"
                align="center"
              />
              <el-table-column
                prop="warehouseName"
                label="所属仓库"
                width="150"
                align="center"
              />
              <el-table-column
                prop="code"
                label="库区编号"
                width="120"
                align="center"
              />
              <el-table-column label="库区名称" prop="areaName" width="120" align="center" />
              <el-table-column label="库位编号" prop="code" width="120" align="center" />
              <el-table-column label="库位名称" prop="name" width="120" align="center" />
              <el-table-column
                label="温度类型"
                width="130"
                align="center"
              >
                <template #default="{ row }">
                  {{ temperature[row.temperatureType] }}
                </template>
              </el-table-column>
              <el-table-column
                label="承重类型"
                width="130"
                align="center"
              >
                <template #default="{ row }">
                  {{ bearing[row.bearingType] }}
                </template>
              </el-table-column>
              <el-table-column
                label="用途属性"
                width="150"
                align="center"
              >
                <template #default="{ row }">
                  {{ use[row.useType] }}
                </template>
              </el-table-column>
              <el-table-column label="停用状态" width="120" align="center">
                <template #default="scope">
                  {{ statup[scope.row.status] }}
                </template>
              </el-table-column>
              <el-table-column label="承载上限" prop="maxNum" width="120" align="center" />
              <el-table-column
                prop="updateTime"
                label="更新时间"
                width="200"
                align="center"
              />
              <el-table-column
                fixed="right"
                label="操作"
                width="200"
                align="center"
              >
                <template #default="{row}">
                  <el-button type="text" size="small" @click="edit(row.id)">编辑</el-button>
                  <el-button type="text" size="small" @click="show(row)">{{ row.status==0?'启用':'停用' }}</el-button>
                  <el-button type="text" size="small">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-divider />
            <!-- 分页 -->
            <el-pagination
              class="page"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="params.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="+total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-card>
        </div>
      </section>
      <!-- 弹窗 -->
      <el-dialog
        :title="title"
        :visible="dialogVisible"
        width="30%"
        @close="closedialog"
      >
        <span>确定要{{ state }} : {{ name }} 吗?</span>
        <span slot="footer" class="dialog-footer">
          <el-button round @click="closedialog">取 消</el-button>
          <el-button type="primary" round @click="submit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 导入库区的弹窗 -->
    <UploadExcel :visible="visible" :before-upload="beforeUpload" :on-success="onSuccess" @importClose="visible=false" />
  </div>
</template>

<script>
import SeachTop from '@/components/SeachTop'
import UploadExcel from '@/components/UploadExcel'
import { locationDetail, importStore, startChange } from '@/api'
export default {
  components: {
    SeachTop,
    UploadExcel
  },
  data() {
    return {
      state: '',
      name: '',
      status: '',
      id: '', // 当前点击行的id
      visible: false, // 导入的弹窗
      dialogVisible: false,
      statup: {
        // 枚举仓库状态
        0: '停用 ',
        1: '启用'
      },
      temperature: { // 温度类型枚举
        LC: '冷藏',
        CW: '常温',
        HW: '恒温'
      },
      bearing: { // 承重类型
        ZX: '重型',
        QX: '轻型'
      },
      use: { // 用途类型
        RKHCQ: ' 入库缓存区',
        CKHCQ: '出库缓存区',
        CCQ: '存储区',
        FJQ: '分拣区',
        ZJQ: '质检区'
      },
      params: { // 查询库位的参数
        areaName: '',
        name: '',
        current: 1,
        size: 10
      },
      total: 0,
      locationList: [] // 库位的数据
    }
  },
  computed: {
    title() {
      return this.status === 0 ? '确认启用' : '确认停用'
    }
  },
  created() {
    this.fetchareaDetail()
  },
  methods: {
    add() { // 薪增库区
      this.$router.push(`/manage-base-info/location/details/null`)
    },
    edit(id) { // 点击编辑
      this.$router.push(`/manage-base-info/location/details/${id}`)
    },
    importload() { // 导入的弹窗
      this.visible = true
    },
    async fetchareaDetail() { // 获取页面数据的方法
      const res = await locationDetail(this.params)
      this.locationList = res.data.records
      this.total = res.data.total
      this.params.size = +res.data.size
    },
    show(row) { // 启停 打开弹窗
      this.dialogVisible = true
      this.status = row.status === 0 ? 1 : 0
      this.name = row.name
      this.id = row.id
      this.state = row.status === 0 ? '启用' : '停用'
    },
    closedialog() {
      this.dialogVisible = false
    },
    async submit() { // 确定启停弹窗关闭
      await startChange({ id: this.id, status: this.status })
      this.$message.success('状态改变ok')
      this.closedialog()
      this.fetchareaDetail()
    },
    handleSizeChange(num) { // 切换每页数量
      this.params.size = num
      this.fetchareaDetail()
    },
    handleCurrentChange(page) { // 切换页数
      this.params.current = page
      this.fetchareaDetail()
    },
    // 上传文件的相关方法
    beforeUpload(file) {
      // 这个函数必须 return 一个布尔值 并且只有 return 出去的是 true 的时候才会执行后续的解析 excel 的操作
      // 如果 reture false，表示校验不通过，不会进行正式的解析操作
      console.log('上传前', file)
      // 文件大小超过 1M 不允许导入
      const isLt1M = file.size / 1024 / 1024 < 1 // 小于1M
      if (isLt1M) {
        return true
      }
      this.$message({
        message: '文件体积不能超过1M',
        type: 'warning'
      })
      return false
    },
    async onSuccess({ results, header }) {
      // results：表体数据
      // header：表头数据
      console.log('上传完成', results, header)
      // 数据转换
      // 中英文对照关系
      const headerRelation = {
        '所属仓库': 'warehouseName',
        '库区编号': 'code',
        '库区名称': 'name',
        '温度类型': 'temperatureType',
        '负责人': 'personName',
        '联系电话': 'phone'
      }
      // 将解析出来的 excel 数据中的表体数据的的 key 换成英文
      const data = this.getImportData(results, headerRelation)
      console.log(data)
      // 调用接口
      await importStore(data)
      // 提示用户
      this.$message.success('批量导入成功')
    },
    // 转换数组中的每一项的对象的 key 值的方法
    getImportData(results, headerRelation) {
      const arr = []
      // 将所有的中文 key 转换成英文 key，然后添加到新数组中
      results.forEach(item => {
        const obj = {}
        Object.keys(item).forEach(key => {
          obj[headerRelation[key]] = item[key]
        })
        arr.push(obj)
      })
      return arr
    }
  }
}
</script>

<style lang="scss">
.app-main {
  background-color: #fdfafa;
  // width: 100%;
  position: relative;
  overflow: hidden;
  margin: 20px 20px;
}
.top {
  margin-bottom: 20px;
}
.formlog {
  display: flex;
  justify-content: space-around;
}
.right {
  margin-top: 65px;
  margin-left: 55px;
}
.new {
  margin-bottom: 15px;
}
.page{
  text-align: center;
}
.btn{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
